const app = getApp()
const { Api } = app.globalData
const page = [1, 1], limit = 6
let isBottom = false
let praising = false

Page({
	data: {
		navs: [
			{ text: '综合' },
			{ text: '热门' },
		],
		nav: 0,
		dynamics: [[], []],
		complete: [false, false]
	},
	onLoad() {
		this.getDynamics()
	},
	getDynamics() {
		let { nav, dynamics, complete } = this.data
		if (!complete[nav]) {
			app.get(Api.dynamic.list, {
				orderBy: nav,
				page: page[nav],
				limit
			}).then(res => {
				if (res.code === 1) {
					dynamics[nav] = dynamics[nav].concat(res.data)
					complete[nav] = res.data.length < limit
					this.setData({
						dynamics, complete
					})
					isBottom = false
					wx.stopPullDownRefresh()
				}
			}).catch(err => {
				console.error(err)
				wx.stopPullDownRefresh()
			})
		}
	},
	navChange(e) {
		this.setData({
			nav: e.detail.nav
		}, () => {
			if (!this.data.dynamics[e.detail.nav].length) {
				this.getDynamics()
			}
		})
	},

	/**
	 * 点赞
	 */
	handlePraise(e) {
		let { index } = e.currentTarget.dataset
		let { dynamics, nav } = this.data
		if (!praising) {
			praising = true
			let praise = !dynamics[nav][index].praised
			console.log(praise)
			this.dynamicUpdateRequest(dynamics[nav][index].id, { praise }).then(() => {
				dynamics[nav][index].praised = praise
				dynamics[nav][index].praise += praise ? 1 : -1
				this.setData({
					dynamics
				})
				praising = false
			}).catch(err => {
				praising = false
			})
		}
	},

	dynamicUpdateRequest(id, data) {
		return new Promise((resolve, reject) => {
			app.post(Api.dynamic.update, {
				...data, id
			}).then(res => {
				res.code === 1 ? resolve() : reject(res)
			}).catch(err => {
				reject(err)
			})
		})
	},

	onReachBottom() {
		if (!isBottom) {
			isBottom = true
			page[this.data.nav] += 1
			this.getDynamics()
		}
	},

	onPullDownRefresh() {
		const { nav } = this.data
		page[nav] = 1
		isBottom = false
		this.setData({
			[`dynamics[${nav}]`]: [],
			[`complete[${nav}]`]: false
		}, _ => {
			this.getDynamics()
		})
	}
})